// ==UserScript==
// @name           Projected Miles for the Year
// @namespace      http://glenncarr.com/greasemonkey
// @description    Display projected miles for the year, and convert kilometers to miles
// @include        http://www.dailymile.com/people/*
// @author         Glenn Carr
// $LastChangedRevision: 625 $
// $LastChangedDate: 2012-04-03 22:01:55 +0000 (Tue, 03 Apr 2012) $
// ==/UserScript==

// from http://lawrence.ecorp.net/inet/samples/js-date-fx.shtml
Date.prototype.copy = function () {
            return new Date(this.getTime());
        };
Date.prototype.getDaysBetween = function(d) {
        var tmp = d.copy();
        tmp.setUTCHours(this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds(), this.getUTCMilliseconds());        
        var time = tmp.getTime() - this.getTime();
        return time/(1000 * 60 * 60 * 24);
    };
Date.prototype.getDayOfYear = function() {
        var start = new Date(this.getFullYear(), 0, 0);
        return this.getDaysBetween(start) * -1;
    };

var milesElement = document.evaluate( '//dl[@id="profile_list"]/dt[contains(.,"Miles:")]/../dd/strong[2]', document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
if ( milesElement.snapshotLength > 0 )
{
	var today = new Date();

	milesElement = milesElement.snapshotItem( 0 );
	var el = document.createElement( 'br' );
	milesElement.parentNode.insertBefore( el, null );
	var el = document.createElement( 'strong' );

	var currentMiles = parseInt( milesElement.innerHTML, 10 );
	var projectedMiles = Math.round( 365 * currentMiles / today.getDayOfYear() * 100 ) / 100;

	el.innerHTML = projectedMiles;
	milesElement.parentNode.insertBefore( el, null );
	var el = document.createElement( 'span' );
	
	el.innerHTML = ' projected for ' + today.getFullYear();
	milesElement.parentNode.insertBefore( el, null );

	var el = document.createElement( 'br' );
	milesElement.parentNode.insertBefore( el, null );
	var el = document.createElement( 'span' );
	var perDay = Math.round( currentMiles / today.getDayOfYear() * 100 ) / 100;
	el.innerHTML = 'Average <strong>' + perDay + '</strong> / day (' + today.getDayOfYear() + ' days)';
	milesElement.parentNode.insertBefore( el, null );
}
